package com.tdam2011.grupo02.messagesender;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;

import com.tdam2011.grupo02.R;
import com.tdam2011.grupo02.data.DatabaseHelperSingleton;
import com.tdam2011.grupo02.domain.MensajeWeb;
import com.tdam2011.grupo02.domain.Usuario;
import com.tdam2011.grupo02.support.MapLocationController;
import com.tdam2011.grupo02.ui.MensajeriaWebFragmentActivity;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Binder;
import android.os.IBinder;
import android.util.Log;

public class UpdateMessagesService extends Service {

	private NotificationManager notificationManager;
	private int NOTIFICATION = R.string.serviceNotificationTitle;
	private SimpleDateFormat dateFormat = new SimpleDateFormat(
			"dd/MM/yyyy HH:mm:ss");

	private final IBinder binder = new LocalBinder();

	private static final String TAG = "UpdateMessagesService";

	@Override
	public IBinder onBind(Intent arg0) {
		return binder;
	}

	@Override
	public void onCreate() {
		Log.d(TAG, "onCreate");
		notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);

		super.onCreate();
	}

	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		Log.d(TAG, "intent = " + intent.getAction());

		Usuario user = DatabaseHelperSingleton
				.getInstance(UpdateMessagesService.this).getDatabaseHelper()
				.getUsuario();

		GetReceivedMessagesTask receivedMessagesTask = new GetReceivedMessagesTask();
		receivedMessagesTask.execute(user.get_id(), user.getPassword());

		return super.onStartCommand(intent, flags, startId);
	}

	@Override
	public void onDestroy() {
		// TODO stop to any network traansaction, don't save de data (or do it)
		super.onDestroy();
	}

	private void showNotification() {
		Notification notification = new Notification(R.drawable.icon_app,
				getString(R.string.serviceNotificationTitle),
				System.currentTimeMillis());

		PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
				new Intent(this, MensajeriaWebFragmentActivity.class), 0);

		notification.setLatestEventInfo(this,
				getString(R.string.serviceNotificationTitle),
				getString(R.string.serviceNotificationMessage), contentIntent);
		
		notification.flags |= Notification.FLAG_AUTO_CANCEL;
		notification.defaults |= Notification.DEFAULT_SOUND;

		notificationManager.notify(NOTIFICATION, notification);
	}

	public class LocalBinder extends Binder {
		UpdateMessagesService getService() {
			return UpdateMessagesService.this;
		}
	}

	protected class GetReceivedMessagesTask extends
			AsyncTask<String, Integer, ArrayList<ReceivedMessageInfo>> {

		@Override
		protected ArrayList<ReceivedMessageInfo> doInBackground(
				String... params) { 
			String timestamp = DatabaseHelperSingleton
					.getInstance(UpdateMessagesService.this)
					.getDatabaseHelper().lastMsgwTimestamp();

			ArrayList<ReceivedMessageInfo> receivedMessages = WebServiceSingleton
					.getInstance(params[0], params[1]).getMessages(timestamp);
			return receivedMessages;
		}

		@Override
		protected void onPostExecute(
				ArrayList<ReceivedMessageInfo> receivedMessages) {
			super.onPostExecute(receivedMessages);

			for (ReceivedMessageInfo receivedMessage : receivedMessages)
				if (receivedMessage.getCode() == WebServiceInfo.SUCCESS
						&& receivedMessage.getTimestamp() != null) {
					MensajeWeb webMessage = new MensajeWeb();
					webMessage.setContacto(receivedMessage.getFrom());
					
					try {
						webMessage.setFecha(dateFormat.parse(
								receivedMessage.getTimestamp()).getTime());
					} catch (ParseException e) {
						e.printStackTrace();
					}
					
					String initMessage = receivedMessage.getMessage();
					String message = MapLocationController.parseMessage(initMessage);
										
					webMessage.setContactLocation(MapLocationController.parseLocation(UpdateMessagesService.this,initMessage));					
					webMessage.setMensaje(message);
					webMessage.setTipo(MensajeWeb.TYPE_RECEIVED);
										
					DatabaseHelperSingleton
							.getInstance(UpdateMessagesService.this)
							.getDatabaseHelper().addMsgw(webMessage);

					showNotification();
				}
		}
	}
}
